<?php
/* SVN FILE: $Id: item_tempgroupchange.php 247 2009-10-22 15:31:39Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* Temporary Group Change item
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 247 $
* @lastrevision $Date: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/items/own/item_tempgroupchange.php $
*/

class item_tempgroupchange extends templateItem
{
	/**
	 * Enable the ability
	 * Settable
	 *
	 * @access	protected
	 * @var		string
	 */
	const ableToSelectAdmin = false;
	
	/**
	 * The default name of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultName = "Temporary Change Group";
	
	/**
	 * The default description of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultDescription = "Change your group to {group_name} for a limited time";
	
	// Inherited Properties
	/**
	 * Item setting to allow multiple instances within ibMarket 
	 *
	 * @access	protected
	 * @var		boolean
	 */
	protected $allowMultiple = true;
	
	/**
	 * Item specific setting
	 *
	 * @access	protected
	 * @var		array
	 */
	protected $itemSettings = array();
	
	/**
	 * The description of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $itemDescription;
	
	/**
	 * Constructor to setup the item
	 *
	 * @access	public
	 * @param	ipsRegistry	$registry	IPB registry
	 * @param	array		&$item		The item information
	 */
	public function __construct(ipsRegistry $registry, array &$item)
	{
		parent::__construct($registry, $item);
		
		if($item['item_config'] || $item['item_id'] != 0)
		{
			$this->itemSettings = unserialize($item['item_config']);
			
			$this->item['item_name'] = str_replace('{group_name}',$this->caches['group_cache'][$this->itemSettings['group_id']]['g_title'],$this->item['item_name']);
		}
		else
		{
			$this->itemSettings['group_id'] = $this->settings['member_group'];
			$this->itemSettings['lasting'] = 1;
			$this->itemSettings['time_unit'] = 86400;
		}
		
		$this->itemDescription = str_replace('{group_name}',$this->caches['group_cache'][$this->itemSettings['group_id']]['g_title'],$this->item['item_description']);
		
		if((!marketRegistry::limitUpdate || marketRegistry::$UPDATE < self::limitUpdate) && $this->ipsclass->input['request_method'] != 'post' && IPB_THIS_SCRIPT == 'public')
		{
			$this->DB->build(array('select'=>'member_id,old_mgroup','from'=>'members','where'=>"end_mgroup > 0 AND end_mgroup < ".IPS_UNIX_TIME_NOW));
			$q = $this->DB->execute();
			if($this->DB->getTotalRows())
			{
				$this->DB->update('members','member_group_id=old_mgroup,old_mgroup=0,end_mgroup=0',"end_mgroup > 0 AND end_mgroup < ".IPS_UNIX_TIME_NOW,false,true);
				while($member = $this->DB->fetch($q))
				{
					IPSLib::runMemberSync( 'onGroupChange', $member['member_id'], $member['old_mgroup'] );
				}
				marketRegistry::$UPDATE++;
			}
		}
	}
	
	/**
	 * Additional settings when adding/editing the item
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminForm()
	{
		$groups = array();
		foreach($this->caches['group_cache'] as $group_id => $group)
		{
			if($group_id == $this->settings['guest_group'] || $group_id == $this->settings['auth_group'])
			{
				continue;
			}
			
			if(!$group['g_access_cp'] || self::ableToSelectAdmin)
			{
				$groups[] = array($group_id,$group['g_title']);
			}
		}
		
		$timeUnits = array(array(3600,$this->lang->words['hours']),array(86400,$this->lang->words['days']),array(604800,$this->lang->words['weeks']));
		
		$form['group_id'] = ipsRegistry::getClass('output')->formDropdown('item[group_id]', $groups, $this->itemSettings['group_id']);
		$form['lasting'] = ipsRegistry::getClass('output')->formSimpleInput('item[lasting]', $this->itemSettings['lasting']);
		$form['time_unit'] = ipsRegistry::getClass('output')->formDropdown('item[time_unit]', $timeUnits, $this->itemSettings['time_unit']);
		return <<<EOF
				<li>
					<label>{$this->lang->words['tags_for_description']}</label>
					<div style='display: inline-block'>
						{group_name} = {$this->lang->words['group_tag']}
						<br />
						{$this->lang->words['tags_settable']}
					</div>
				</li>
				<li>
					<label>{$this->lang->words['which_group']}</label>
					{$form['group_id']}
				</li>
				<li>
					<label>{$this->lang->words['group_change_lasts']}</label>
					<div style='display: inline-block'>
						{$form['lasting']}
						{$form['time_unit']}
					</div>
				</li>

EOF;
	}
	
	/**
	 * Saving to adding/editing the item
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	array	[$input]		Relavent input relating to the item
	 * @todo
	 * @return	void
	 */
	public function adminSave(array &$item_info, array $input)
	{
		$setting = array();
		$setting['group_id'] = intval($input['group_id']);
		$setting['lasting'] = intval($input['lasting']);
		$setting['time_unit'] = intval($input['time_unit']);
		
		$item_info['item_config'] = serialize($setting);
		
		if($this->DB->checkForField("old_mgroup", "members"))
		{
			$this->DB->changeField("members","old_mgroup","old_mgroup","int NOT NULL","'0'");
			$this->DB->changeField("members","end_mgroup","end_mgroup","int NOT NULL","'0'");
		}
		else
		{
			$this->DB->addField("members","old_mgroup","int NOT NULL","'0'");
			$this->DB->addField("members","end_mgroup","int NOT NULL","'0'");
		}
	}
	
	/**
	 * When quick saving the price and stock
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	string	$type			Possible values: 'stockprice', more possibly in the future
	 * @return	void
	 */
	public function adminQuickSave(array &$item_info, $type)
	{
		return;
	}
	
	/**
	 * When removing the item from ibMarket
	 *
	 * @access	public
	 * @return	void
	 */
	public function adminRemove()
	{
		if(count(marketRegistry::getItemsByFiles($this->item['filename'])) == 1)
		{
			if(!isset($this->request['restore_groups']))
			{
				$this->registry->getClass('class_localization')->loadLanguageFile( array( 'admin_item_language' ) );
				
				$form['restore'] = ipsRegistry::getClass('output')->formYesNo('restore_groups', 1);
				
				$this->registry->output->html = <<<EOF
<div class='section_title'>
	<h2>{$this->lang->words['delete_item_title']}</h2>
</div>

<div id='deleteItemForm'>
	<form method='post' action='{$this->settings['base_url']}module=items&amp;section=delete&amp;do=delete' id='itemForm'>
		<input type='hidden' name='item_id' value='{$this->item['item_id']}' />
		<div class='acp-box'>
			<h3>{$this->lang->words['delete_item_table']}</h3>
			<ul class='acp-form alternate_rows'>
				<li>
					<label>
						{$this->lang->words['restore_groups']}
						<span class="desctext">{$this->lang->words['restore_groups_desc']}</span>
					</label>
					{$form['restore']}
				</li>
			</ul>
			<div class='acp-actionbar'>
				<div class='centeraction'>
					<input type='submit' value='{$this->lang->words['delete_item_button']}' class='button primary'>
				</div>
			</div>
		</div>
	</form>
</div>
EOF;
				
				$this->registry->getClass('output')->html_main .= $this->registry->getClass('output')->global_template->global_frame_wrapper();
				$this->registry->getClass('output')->sendOutput();
			}
			else
			{
				if($this->request['restore_groups'])
				{
					$this->DB->build(array('select'=>'member_id,old_mgroup','from'=>'members','where'=>"end_mgroup > 0"));
					$q = $this->DB->execute();
					if($this->DB->getTotalRows())
					{
						$this->DB->update('members','member_group_id=old_mgroup,old_mgroup=0,end_mgroup=0',"end_mgroup > 0",false,true);
						while($member = $this->DB->fetch($q))
						{
							IPSLib::runMemberSync( 'onGroupChange', $member['member_id'], $member['old_mgroup'] );
						}
					}
				}
				$this->DB->dropField("members","old_mgroup");
				$this->DB->dropField("members","end_mgroup");
			}
		}
	}
	
	/**
	 * Viewing the file edits if any
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminViewFileEdits()
	{
		return false;
	}
	
	/**
	 * Any admin AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function adminAjax()
	{
		return;
	}
	
	/**
	 * Check and modify the intentory item information before storing in the database
	 *
	 * @access	public
	 * @param	array	&$invItem		The new inventory item information to be stored in the database.
	 * @return	bool	true if the item is successfully created, false otherwise
	 */
	public function publicOnCreateItem(array &$invItem)
	{
		return true;
	}
	
	/**
	 * When using the item
	 * Show a form and validate the form
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	string|bool				string if there is a form to be used, true if successfully used, false otherwise
	 */
	public function publicUseItem(array &$invItem)
	{
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'public_items' ) );
		
		if($this->itemSettings['group_id'] == $this->memberData['member_group_id'])
		{
			$this->registry->getClass('output')->showError('you_in_group');
		}
		
		if($this->memberData['old_mgroup'])
		{
			$this->registry->getClass('output')->showError('used_temp_group_already');
		}
		
		IPSMember::save( $this->memberData['member_id'], array( 'core' => array( 'member_group_id' => $this->itemSettings['group_id'], 'old_mgroup' => $this->memberData['member_group_id'], 'end_mgroup' => IPS_UNIX_TIME_NOW + $this->itemSettings['lasting'] * $this->itemSettings['time_unit'] ) ) );
		
		IPSLib::runMemberSync( 'onGroupChange', $this->memberData['member_id'], $this->itemSettings['group_id'] );
		
		$this->writeLog($invItem, "Changed group from ".$this->caches['group_cache'][$this->memberData['member_group_id']]['g_title']." to ".$this->ipsclass->cache['group_cache'][$this->itemSettings['group_id']]['g_title']." for a limited time");
		
		$this->deleteItems($invItem);
		
		$this->lang->words['change_to_x_group'] = sprintf($this->lang->words['change_to_x_group'], $this->caches['group_cache'][$this->itemSettings['group_id']]['g_title']);
		$this->registry->getClass('output')->redirectScreen( $this->lang->words['change_to_x_group'], $this->settings['base_url_with_app'] . "module=inventory" );
	}
	
	/**
	 * Any AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function publicAjax(array &$invItem)
	{
		return;
	}
	
	/**
	 * When the item is being sold back
	 *
	 * @access	public
	 * @param	array	&$invItem	The inventory item information
	 * @return	bool				true if successful, false otherwise
	 */
	public function publicOnResoldItem(array &$invItem)
	{
		return true;
	}
	
	/**
	 * When the item is being restocked
	 *
	 * @access	public
	 * @param	array	&$item	The inventory item information
	 * @return	void
	 */
	public function onItemRestock(array &$item)
	{
		return;
	}
	
	/**
	 * Get the description of the item, normally called when there is no intentory item being used
	 *
	 * @access	public
	 * @return	string
	 */
	public function parseStoreDescription()
	{
		return $this->itemDescription;
	}
	
	/**
	 * Get the description of the item, normally called when there is one intentory items being used
	 *
	 * @access	public
	 * @param	array	$invItem	The inventory item information
	 * @return	string
	 */
	public function parseInventoryDescription(array $invItem)
	{
		return $this->itemDescription;
	}
}
